package servlet;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import facade.Producto.FacadeProducto;

/**
 * Servlet implementation class DescargarPDFProducto
 */
public class DescargarPDFProducto extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DescargarPDFProducto() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		try{
			String id_producto=request.getParameter("id_producto");
			
			System.out.println("id_producto --> "+id_producto);
			
			if(id_producto!=null ){				
				//ver producto
				ByteArrayOutputStream baosPDF = new ByteArrayOutputStream() ;
					      
				baosPDF = obtenerArchivoPdfReporte(Integer.parseInt(id_producto));
				
				if(baosPDF!=null && baosPDF.size()>0){
					// setting some response headers
					response.setHeader("Expires", "0");
					response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
					response.setHeader("Pragma", "public");
		            // setting the content type
					response.setContentType("application/pdf");
		            // the contentlength
					response.setContentLength(baosPDF.size());
		            // write ByteArrayOutputStream to the ServletOutputStream
		            OutputStream os = response.getOutputStream();
		            baosPDF.writeTo(os);
		            os.flush();
		            os.close();
	            }else{
	            	response.getWriter().println("VISTA PREVIA NO DISPONIBLE ");
	            }
			
			}else{
				response.getWriter().println("VISTA PREVIA NO DISPONIBLE ");
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	
	static public  ByteArrayOutputStream obtenerArchivoPdfReporte(int id_producto){
    	ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    	try {	
    		//String path = SrcProperties.DOCUMENTS_PATH() + File.separator + id_producto+ ".pdf";
    		
    		//Obtenemos la ruta del pdf
    		FacadeProducto fp = new FacadeProducto();
    		String path = fp.obtenerPathProducto(id_producto);
    		
    		if(new File(path).exists()){
    			baosPDF.write(getBytesFromFile(new File(path)));
    			baosPDF.close();
    		}
		 } catch (Exception e) {
		    e.printStackTrace();
		 }
		 return baosPDF;
    }
	
	public static byte[] getBytesFromFile(File file) throws IOException {
        InputStream is = new FileInputStream(file);
    
        // Get the size of the file
        long length = file.length();
    
        if (length > Integer.MAX_VALUE) {
            // File is too large
        }
    
        // Create the byte array to hold the data
        byte[] bytes = new byte[(int)length];
    
        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length
               && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
            offset += numRead;
        }
    
        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "+file.getName());
        }
    
        // Close the input stream and return bytes
        is.close();
        return bytes;
    }

}
